<template>
	<van-list
		v-model="loading"
		:finished="finished"
		finished-text="没有更多了"
		:error="error"
		error-text="加载失败，请点击重试"
		@load="onLoad"
    :immediate-check="false" 
	>
		<comment-item
			v-for="(item, index) in list"
			:key="index"
			:comment="item"
			@reply-click="$emit('reply-click', $event)"
		/>
		<!-- <van-cell
			v-for="(item, index) in list"
			:key="index"
			:title="item.content"
		></van-cell> -->
	</van-list>
</template>
<script>
import { getComments } from '@/api/comment'

import CommentItem from './comment-item.vue'
export default {
	name: 'CommentList',
	components: {
		CommentItem,
	},
	props: {
		source: {
			type: [Number, String, Object],
			required: true,
		},
		list:{
		  type:Array,
		  default:()=>[]
		},
    type:{
      type:String,
      validator(value){
        return ['a','c'].includes(value)
      },
      default:'a'
    }
	},
	data() {
		return {
			// list: [], // 评论列表
			loading: false, // 上拉加载更多的 loading
			finished: false, // 是否加载结束
			offset: null, // 获取下一页数据的标记
			limit: 10,
			error: false,
		}
	},
	created() {
    // 手动开启loading
    this.loading = true
		this.onLoad()
	},
	methods: {
		async onLoad() {
			try {
				const { data } = await getComments({
					type: this.type,
					source: this.source.toString(), //大数字需要转为字符串；对比接口是params-查询字符串；如果直接在url地址隐式转换为字符
					offset: this.offset,
					limit: this.limit,
				})
				// console.log(data)
				const { results } = data.data
				this.list.push(...results)
				// 展示评论数量
				this.$emit('onload-success', data.data)
				//  修改loadin状态
				this.loading = false
				if (results.length) {
					// 有数据，更新下一页
					this.offset = data.data.last_id
				} else {
					this.finished = true
				}
			} catch (err) {
				console.log(err)
				this.error = true
				this.loading = false
			}
		},
	},
}
</script>
